﻿using System;
using System.Windows.Controls;
using Microsoft.Extensions.DependencyInjection;
using RotovapPlatform.UI.ViewModels.MaterialManagement;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Threading;
using System.Windows;

namespace RotovapPlatform.UI.Views.MaterialManagement
{
	public partial class MaterialManagementView : UserControl
	{
		private readonly ShelfViewModel _viewModel;

		public MaterialManagementView()
		{
			InitializeComponent();

			// 获取ShelfViewModel实例
			_viewModel = App.ServiceProvider.GetRequiredService<ShelfViewModel>();

			// 设置ShelfView的DataContext
			ShelfViewControl.DataContext = _viewModel;

			// 订阅Loaded事件，确保在视图加载时刷新数据
			this.Loaded += MaterialManagementView_Loaded;
		}

		private void MaterialManagementView_Loaded(object sender, RoutedEventArgs e)
		{
			Task.Run(async () =>
			{
				await Dispatcher.InvokeAsync(async () =>
				{
					Debug.WriteLine("MaterialManagementView: 视图已加载，开始刷新数据");

					try
					{
						// 检查数据是否已存在，如果已存在则跳过刷新
						if (_viewModel.OccupiedSlots.Count > 0)
						{
							Debug.WriteLine("MaterialManagementView: 控件已加载，但数据已存在，跳过刷新");

							// 仅强制刷新UI，不重新加载数据
							ShelfViewControl.ForceRefreshUI();
							return;
						}

						// 刷新货架数据
						await _viewModel.RefreshDataAsync();

						// 强制刷新UI
						ShelfViewControl.ForceRefreshUI();

						Debug.WriteLine("MaterialManagementView: 数据刷新完成");
					}
					catch (Exception ex)
					{
						Debug.WriteLine($"MaterialManagementView: 刷新数据时发生错误: {ex.Message}");
					}
				});
			});
		}
	}
}